﻿using Cookbook.ViewModels;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Storage.Streams;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace Cookbook.Views
{
  /// <summary>
  /// An empty page that can be used on its own or navigated to within a Frame.
  /// </summary>
  public sealed partial class RecipesView : Page
  {
    private RecipesViewModel viewModel;

    public RecipesView()
    {
      this.InitializeComponent();
    }

    protected override async void OnNavigatedTo(NavigationEventArgs e)
    {
      base.OnNavigatedTo(e);

      this.viewModel = new RecipesViewModel();
      this.DataContext = viewModel;

      await viewModel.LoadRecipes();
    }

    private async void suggestionsRequested(SearchBox sender, SearchBoxSuggestionsRequestedEventArgs args)
    {
      var queryText = args.QueryText.ToLower();

      if (string.IsNullOrWhiteSpace(queryText))
      {
        return;
      }

      // deferral is needed due to use of async/await
      var deferral = args.Request.GetDeferral();

      var recipes = await viewModel.Search(queryText);
      
      // add suggestions
      args.Request.SearchSuggestionCollection.AppendQuerySuggestions(recipes.Select(p => p.Title));

      // add result
      var exactMatch = recipes.FirstOrDefault(p => p.Title.ToLower() == queryText);
      if (exactMatch != null)
      {
        var picture = RandomAccessStreamReference.CreateFromUri(new Uri(exactMatch.ImagePath));

        args.Request.SearchSuggestionCollection.AppendResultSuggestion(
            exactMatch.Title,
            string.Empty,
            exactMatch.Id.ToString(),
            picture,
            exactMatch.Title);
      }
      
      // notify that the data is ready
      deferral.Complete();
    }
  }
}
